package information;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.mail.util.MailSSLSocketFactory;


public class QueryMailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String id=request.getParameter("id");
		InformationJdbc information=new InformationJdbc();
		try{
			List<Information> infoList=information.queryInfoById(id);
			for(Information info:infoList){
				String mail=info.getEmail();
				System.out.println(mail);
				MailSSLSocketFactory sf = new MailSSLSocketFactory();
				sf.setTrustAllHosts(true);
				String to = mail;
				String from = "1466926982@qq.com"; //1165088148
				String host = "smtp.qq.com";
				Properties properties = System.getProperties();
				properties.setProperty("mail.smtp.host", host);
				properties.put("mail.smtp.auth", "true");
				Session session = Session.getDefaultInstance(properties,new Authenticator(){
					public PasswordAuthentication getPasswordAuthentication()
					{
						return new PasswordAuthentication("1466926982@qq.com", "bqtqfrkmhzmahagg"); //admraevkllaoifge�������ʼ��û�������Ȩ��
					}
				});
				try{
					double num=Math.random()*10000+1;
					int code=(int) Math.round(num);
					MimeMessage message = new MimeMessage(session);
					message.setFrom(new InternetAddress(from));
					message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
					message.setSubject("密码重置");
					message.setText("您的验证码为"+code);
					Transport.send(message);
					System.out.println("Sent message successfully....from runoob.com");
					request.setAttribute("code",code);
				}catch (MessagingException mex) {
					mex.printStackTrace();
				}
				request.setAttribute("id",id);
				request.setAttribute("infoList",infoList);
				RequestDispatcher dis=request.getRequestDispatcher("Security/MailPsw.jsp");
				dis.forward(request, response);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
